package com.liangtian.mdm.material.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.liangtian.mdm.base.authentication.JWTUtil;
import com.liangtian.mdm.base.constants.ResultCode;
import com.liangtian.mdm.base.controller.BaseController;
import com.liangtian.mdm.base.response.BaseResponse;
import com.liangtian.mdm.dm.common.util.RequestUtils;
import com.liangtian.mdm.material.model.WlbmJldw;
import com.liangtian.mdm.material.service.WlbmJldwService;
import com.liangtian.mdm.system.log.SysLogUtil;
import com.liangtian.mdm.system.log.model.SysLogEnum;
import com.liangtian.mdm.system.user.util.ExcelImport;
import com.liangtian.mdm.util.CheckNotNullUtils;
import com.liangtian.mdm.util.ExportUtil;
import com.liangtian.mdm.util.IoUtil;
import com.liangtian.mdm.util.TemplateName;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.liangtian.mdm.base.constants.MdmConstant.TABLE_NAME_WLBM_JLDW;

@RestController
@RequestMapping("/wlbmJldwController")
public class WlbmJldwController extends BaseController {

    @Autowired
    private WlbmJldwService wlbmJldwService;

    private ExcelImport excelImport = new ExcelImport();

    private List<WlbmJldw> wlbmJldwListByExport = null;
    private Map<String, Object> wlbmJldwmap = null;

    @PostMapping(value = "/queryAllWlbmJldwList")
    public BaseResponse queryAllWlbmJldwList(HttpServletRequest request, WlbmJldw jldw) {
        Map<String, Object> paramMap = RequestUtils.paramToMap(request, WlbmJldw.class, false);
        // 判断属性是否为空
        String nullArg = CheckNotNullUtils.checkMapNotNull(paramMap, "limit");
        if (nullArg != null) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), nullArg + "不能为空");
        }
        PageInfo pageInfo = wlbmJldwService.getWlbmJldwListByCond(paramMap);
        List<WlbmJldw> list = pageInfo.getList();
        wlbmJldwListByExport = list;
        wlbmJldwmap = paramMap;
        for (WlbmJldw jldws : list) {
            String jldwDesc = jldws.getJldwId() + "," + jldws.getJldw() + "," + jldws.getFh();
            jldws.setJldwDesc(jldwDesc);
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rows", list);
        jsonObject.put("total", pageInfo.getTotal());
        return new BaseResponse().ok(jsonObject);
    }

    @PostMapping(value = "/insertWlbmJldw")
    public BaseResponse insertWlbmJldw(WlbmJldw jldw, HttpServletRequest request) {
        String token = (String) SecurityUtils.getSubject().getPrincipal();
        String username = JWTUtil.getUsername(token);
        jldw.setCreater(username);
        //通过jldw字段，查询物料计量单位是否存在
        int count = wlbmJldwService.checkWlbmJldwExist(jldw);
        if (count > 0) {
            return BaseResponse.genResponse(ResultCode.WL_JLDW_HAS_EXIST);
        }
        wlbmJldwService.insertWlbmJldw(jldw);
        SysLogUtil.insertLog("新增物料计量单位[" + jldw.getJldw() + "]",
                SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.XZ.getCode(), request);
        return new BaseResponse().ok("新增物料计量单位成功");
    }

    @PostMapping(value = "/checkWlbmJldwExist")
    public BaseResponse checkWlbmJldwExist(WlbmJldw jldw) {
        //通过jldw和jldwId字段，查询物料计量单位是否存在
        int count = wlbmJldwService.checkWlbmJldwExist(jldw);
        JSONObject result = new JSONObject();
        result.put("exist", count > 0);
        return new BaseResponse().ok(result);
    }

    @PostMapping(value = "/selectWlbmJldwById")
    public BaseResponse selectWlbmJldwById(WlbmJldw jldw) {
        WlbmJldw wlbmjldw = wlbmJldwService.getWlbmJldwByIdOrName(jldw);
        if (wlbmjldw == null) {
            return BaseResponse.genResponse(ResultCode.WL_JLDW_NOT_EXIST);
        }
        return new BaseResponse().ok(wlbmjldw);
    }

    /**
     * 编辑计量单位信息
     */
    @PostMapping(value = "/updateWlbmJldw")
    public BaseResponse updateWlbmJldw(WlbmJldw jldw, HttpServletRequest request) {
        // 判断属性是否为空
        String nullArg = CheckNotNullUtils.checkObjNotNull(jldw, "jldwId", "jldw", "fh", "xz", "zq");
        if (nullArg != null) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), nullArg + "不能为空");
        }
        WlbmJldw wlbmjldw = wlbmJldwService.getWlbmJldwByIdOrName(jldw);
        if (wlbmjldw == null) {
            return BaseResponse.genResponse(ResultCode.WL_JLDW_NOT_EXIST);
        }
        wlbmJldwService.updateWlbmJldw(jldw);
        SysLogUtil.insertLog("编辑物料计量单位[" + jldw.getJldw() + "]",
                SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.BJ.getCode(), request);
        return new BaseResponse().ok("编辑物料计量单位成功");
    }

    @PostMapping(value = "/deleteWlbmJldwByIds")
    public BaseResponse deleteWlbmJldwByIds(HttpServletRequest request) {
        String ids = request.getParameter("ids");
        if (StringUtils.isBlank(ids)) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), "请选择要删除的计量单位");
        }
        String[] idStrList = ids.split(",");
        if (ArrayUtils.isEmpty(idStrList)) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), "计量单位ID列表格式错误");
        }
        int[] idList = Arrays.stream(idStrList).mapToInt(Integer::parseInt).toArray();
        Map<String, Object> map = new HashMap<>(1);
        map.put("idList", idList);
        int ret = wlbmJldwService.deleteWlbmJldwByIds(map);
        if (ret <= 0) {
            return new BaseResponse().fail(ResultCode.DELETE_FAILED.getCode(), "删除物料计量单位失败");
        }
        SysLogUtil.insertLog("删除物料计量单位[" + ids + "]",
                SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.SC.getCode(), request);
        return new BaseResponse().ok("删除物料计量单位成功,删除条数：" + ret);
    }

    @PostMapping(value = "/updateWlbmJldwStatus")
    public BaseResponse updateWlbmJldwStatus(WlbmJldw jldw, HttpServletRequest request) {
        String nullArg = CheckNotNullUtils.checkObjNotNull(jldw, "jldwId", "status");
        if (nullArg != null) {
            return BaseResponse.genResponse(ResultCode.FAIL_REQ_PARAM_ERROR.getCode(), nullArg + "不能为空");
        }
        wlbmJldwService.updateWlbmJldwStatus(jldw);
        if (Integer.parseInt(jldw.getStatus()) == 1) {
            SysLogUtil.insertLog("启用物料计量单位[" + jldw.getJldwId() + "]",
                    SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.QY.getCode(), request);
        } else if (Integer.parseInt(jldw.getStatus()) == 2) {
            SysLogUtil.insertLog("停用用物料计量单位[" + jldw.getJldwId() + "]",
                    SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.TY.getCode(), request);
        }
        return new BaseResponse().ok("修改物料计量单位状态成功");
    }

    @PostMapping(value = "/queryWlbmJldws")
    public BaseResponse queryWlbmJldws() {
        List<WlbmJldw> jldwList = wlbmJldwService.queryWlbmJldws();
        for (WlbmJldw jldwInfo : jldwList) {
            String jldwDesc = StringUtils.joinWith(",", jldwInfo.getJldwId(), jldwInfo.getJldw(), jldwInfo.getFh());
            jldwInfo.setJldwDesc(jldwDesc);
        }
        return new BaseResponse().ok(jldwList);
    }

    /**
     * 批量导入计量单位
     */
    @PostMapping(value = "/excelImport")
    public BaseResponse excelImport(HttpServletRequest request) {
        BaseResponse baseResponse = new BaseResponse().ok();
        try {
            MultipartHttpServletRequest mulRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = mulRequest.getFile("excel");
            // 获取路径
            String ctxPath = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator;
            // 创建文件
            File dirPath = new File(ctxPath);
            SysLogUtil.insertLog("批量导入物料计量单位",
                    SysLogEnum.WLBM_JLDW.getCode(), SysLogEnum.PD.getCode(), request);
            if (!dirPath.exists()) {
                dirPath.mkdir();
            }
            File uploadFile = new File(ctxPath + file.getOriginalFilename());

            // 保存上传的文件到服务器发布项目中的upload文件夹下
            FileCopyUtils.copy(file.getBytes(), uploadFile);

            Workbook book = ExcelImport.getWorkbook(uploadFile);
            // 得到sheet总数
            int sheetNum = book.getNumberOfSheets();
            for (int i = 0; i < sheetNum; i++) {
                Sheet sheet = book.getSheetAt(i);
                List<Object[]> valueList = ExcelImport.read(sheet);
                // 插入数据
                if (CollectionUtils.isNotEmpty(valueList)) {
                    baseResponse = wlbmJldwService.checkImportListThenInsert(valueList, TABLE_NAME_WLBM_JLDW);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return BaseResponse.genResponse(ResultCode.FAIL);
        }
        return baseResponse;
    }

    /**
     * 下载导入模板
     */
    @GetMapping(value = "/wlbmJldwExport")
    public void wlbmJldwExport(HttpServletResponse response, HttpServletRequest request) {
        //此处存放模板地址
        String path = IoUtil.getTemplatePath();
        //服务器上存的文件名
        String fileName = TemplateName.WLBM_JLDW_TEMPLATE;
        //给用户下载看到的文件名
        String uploadFileName = "计量单位导入模板";
        ExportUtil.exportTemplate(path, fileName, uploadFileName, response);
    }

    /**
     * 导出当前页数据
     */
    @GetMapping(value = "wlLbJldwExportExcel")
    public void wlLbJldwExportExcel(HttpServletResponse response, HttpServletRequest request) {
        if (CollectionUtils.isNotEmpty(wlbmJldwListByExport)) {
            wlbmJldwService.exportWlbmJldw(wlbmJldwListByExport, response);
        }
    }

    /**
     * 导出所有数据
     */
    @GetMapping(value = "wlLbJldwExportExcel2")
    public void wlLbJldwExportExcel2(HttpServletResponse response, HttpServletRequest request) {
        List<WlbmJldw> jldwList = wlbmJldwService.queryWlbmJldws();
        if (CollectionUtils.isNotEmpty(jldwList)) {
            wlbmJldwService.exportWlbmJldw(jldwList, response);
        }
    }

}
